package cn.xiaolang.function.json.jacksonVsRegex;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JsonReadHelper {

	/**
	 * 从json字符串中获取对应字段的值(字符串字段)
	 * 
	 * @param jsonstr
	 *            json字符串
	 * @param fieldname
	 *            字段名
	 */
	public static String getValueByStrField(String jsonstr, String fieldname) {
		Pattern pattern = Pattern.compile("\"" + fieldname + "\":\"(.*?)\"[,|}]");
		Matcher matcher = pattern.matcher(jsonstr);
		return matcher.find() ? matcher.group(1) : null;
	}

	/**
	 * 从json字符串中获取对应字段的值(非字符串字段)
	 * 
	 * @param jsonstr
	 *            json字符串
	 * @param fieldname
	 *            字段名
	 */
	public static String getValueByField(String jsonstr, String fieldname) {
		Pattern pattern = Pattern.compile("\"" + fieldname + "\":(.*?)[,|}]");
		Matcher matcher = pattern.matcher(jsonstr);
		return matcher.find() ? matcher.group(1) : null;
	}

	/**
	 * 从json字符串中获取对应字段的值的集合(字符串字段)
	 * 
	 * @param jsonstr
	 *            json字符串
	 * @param fieldname
	 *            字段名
	 */
	public static List<String> getListByStrField(String jsonstr, String fieldname) {
		Pattern pattern = Pattern.compile("\"" + fieldname + "\":\"(.*?)\"[,|}]");
		Matcher matcher = pattern.matcher(jsonstr);
		List<String> strs = new ArrayList<>();
		while (matcher.find()) {
			strs.add(matcher.group(1));
		}
		return strs;
	}

	/**
	 * 从json字符串中获取对应字段的值的集合(非字符串字段)
	 * 
	 * @param jsonstr
	 *            json字符串
	 * @param fieldname
	 *            字段名
	 */
	public static List<String> getListByField(String jsonstr, String fieldname) {
		Pattern pattern = Pattern.compile("\"" + fieldname + "\":(.*?)[,|}]");
		Matcher matcher = pattern.matcher(jsonstr);
		List<String> strs = new ArrayList<>();
		while (matcher.find()) {
			strs.add(matcher.group(1));
		}
		return strs;
	}
}
